<template>
    <div class="container" :id="container" ref="chartRef"></div>
</template>

<script lang="ts" setup>
import { markRaw, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import * as charts from 'echarts'
import { pxToRem } from '@/utils'

const props = defineProps({
    options: {
        type: Object,
        require: true
    },
    width: {
        type: Number,
        require: false
    },
    height: {
        type: Number,
        default: 200
    },
    top: {
        type: Number,
        default: 0
    },
    isFirst: {
        type: Boolean,
        default: false
    },
    container: {
        type: String,
        default: 'container'
    }
})
const chartRef = ref()
const Aecharts: any = reactive({ value: '' })
const emits = defineEmits(['getEcharts'])

const changeEcharts = (options: any) => {
    Aecharts.value.setOption(options)
    if (props.isFirst) {
        let index = 0
        Aecharts.value.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: 0
        })
        Aecharts.value.on('mouseover', (e: any) => {
            if (e.dataIndex !== index) {
                Aecharts.value.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: index
                })
            } else {
                Aecharts.value.dispatchAction({
                    type: 'highlight',
                    seriesIndex: 0,
                    dataIndex: e.dataIndex
                })
            }
        })
        Aecharts.value.on('mouseout', (e: any) => {
            index = e.dataIndex
            Aecharts.value.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: e.dataIndex
            })
        })
    }
}

watch(
    () => props.options,
    newval => {
        changeEcharts(newval)
    },
    {
        deep: true
    }
)

watch(
    () => props.container,
    newval => {
        nextTick(() => {
            if (chartRef.value) {
                Aecharts.value = markRaw(charts.init(chartRef.value))
                emits('getEcharts', Aecharts.value)
            }
            changeEcharts(props.options)
        })
    },
    {
        immediate: true
    }
)
const Resize = () => {
    Aecharts.value.resize()
}

onMounted(() => {
    chartRef.value.style.width = pxToRem(props.width!)
    chartRef.value.style.height = pxToRem(props.height!)
    window.addEventListener('resize', Resize)
})
onUnmounted(() => {
    window.removeEventListener('resize', Resize)
})
</script>

<style lang="scss" scoped>
.container {
    width: v-bind('props.width');
    height: v-bind('props.height');
    margin-top: v-bind('props.top');
    border-radius: 8px;
}
</style>
